﻿namespace CEIT.MVC3.Web.Controllers
{
    using System;
    using System.Collections.Generic;
    using System.Web.Mvc;
    using System.Web.Security;
    using CEIT.Domain;
    using CEIT.Infrastructure.Queries.Authentication;
    using CEIT.Infrastructure.Queries.Usuario;
    using SharpArch.NHibernate.Contracts.Repositories;
    using SharpArch.NHibernate.Web.Mvc;
    using CEIT.GlobalResources;

    [HandleError]
    public class HomeController : ControllerCustom
    {
        private readonly IAuthenticationService _authenticationService;
        private readonly INHibernateRepository<LogAcesso> _LogAcessoRepository;

        private readonly INHibernateRepository<Usuario> _UsuarioRepository;
        private readonly IUsuarioQuery _UsuarioQueryRepository;

        public HomeController(IAuthenticationService _authenticationService, INHibernateRepository<LogAcesso> LogAcessoRepository)
        {
            this._authenticationService = _authenticationService;
            this._LogAcessoRepository = LogAcessoRepository;
        }

        [Authorize()]
        public ActionResult Index()
        {
            try
            {
                var user = _authenticationService.GetUserAuthenticated();
                ViewBag.UsuarioLogado = user.NmLogin;
            }
            catch (Exception ex)
            {
                _ObjLog.Error("HomeController(Index): " + ex.ToString());
                _Feedback = GlobalResources.Sistema.Feedback.ERROR_SYSTEM;
            }

            return View();
        }

        [HttpPost]
        [Transaction]
        public ActionResult Login(Usuario usuario, FormCollection collection)
        {
            try
            {
                TryUpdateModel(usuario, collection);
                if (ModelState.IsValid && !string.IsNullOrEmpty(usuario.NmLogin) && !string.IsNullOrEmpty(usuario.NmSenha))
                {
                    var usr = this._UsuarioQueryRepository.ValidateUser(usuario);
                    if (usr == null)
                        ModelState.AddModelError("", GlobalResources.Sistema.Feedback.ERROR_INVALID_LOGON);
                    else
                    {
                        this._authenticationService.SignIn(usr, false);
                        return RedirectToAction("Index");
                    }
                }
            }
            catch (Exception ex)
            {
                _ObjLog.Error("Home(Login[]): " + ex.ToString());
                _Feedback = GlobalResources.Sistema.Feedback.ERROR_SYSTEM;
            }
            return View(usuario);
        }

        public ActionResult Login()
        {
            try
            {
                this.LogOff();
            }
            catch (Exception ex)
            {
                _ObjLog.Error("Home(Login): " + ex.ToString());
                _Feedback = GlobalResources.Sistema.Feedback.ERROR_SYSTEM;
            }
            return View();
        }

        public ActionResult LogOff()
        {
            try
            {
                this._authenticationService.SignOut();
            }
            catch (Exception ex)
            {
                _ObjLog.Error("HomeController(LogOff): " + ex.ToString());
                _Feedback = GlobalResources.Sistema.Feedback.ERROR_SYSTEM;
            }
            return RedirectToAction("LogIn");
        }

        /// <summary>
        /// p.eduardo.silva - 20130226:
        /// Gera dados básicos porem necessário para iniciar o sistema
        /// </summary>
        private void AutoGenerator()
        {
            Usuario root = GeneratorRoot();
            if (root != null)
            {
            }
        }

        /// <summary>
        /// Gera superusuario do sistema se nao estiver presente
        /// </summary>
        /// <returns></returns>
        public Usuario GeneratorRoot()
        {
            try
            {
                var root = this._UsuarioQueryRepository.GetRoot();
                if (root == null)
                {
                    root = new Usuario();
                    root.NmSenha = FormsAuthentication.HashPasswordForStoringInConfigFile(_PassRoot, "SHA1");
                    root.NmLogin = _LoginRoot;
                    root.IsRoot = true;
                    this._UsuarioRepository.SaveOrUpdate(root);
                }
                return root;
            }
            catch (Exception ex)
            {
                _ObjLog.Error("Home(GeneratorRoot): " + ex.ToString());
                throw ex;
            }
        }

        public ActionResult Generator()
        {
            AutoGenerator();
            return RedirectToAction("Login");
        }

    }
}
